package cn.yunyichina.provider.clinic.listener;

import cn.yunyichina.provider.clinic.service.impl.AsmServiceImpl;
import cn.yunyichina.provider.clinic.service.impl.PayServiceImpl;
import cn.yunyichina.provider.clinic.utils.DateUtils;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangkewen on 2017/8/23.
 */
public class AsmAlipayMessageListener implements MessageListener<Integer, String> {

    private Logger logger = LoggerFactory.getLogger(AsmAlipayMessageListener.class);


    @Autowired
    private AsmServiceImpl asmService;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onMessage(ConsumerRecord<Integer, String> data) {
        String jsonStr = data.value();
        String orderNo="";
        logger.info("AsmAlipayMessageListener.onMessage.jsonStr -> {}", jsonStr);

        try {
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            orderNo = (String) jsonObject.get("out_trade_no");
            String openId = (String) jsonObject.get("buyer_id");
            String appId = (String) jsonObject.get("app_id");
            String tradeNo = (String) jsonObject.get("trade_no");
            String payMode = (String) jsonObject.get("pay_mode");
            BigDecimal payAmount = jsonObject.getBigDecimal("total_amount").multiply(new BigDecimal(100));

            Map<String, String> params = new HashMap<>();
            OrderExtVo order = new OrderExtVo();
            params.put("order_no",orderNo);
            Response response = BaseService.callHumpFromInternal("yyt.base.order.by.orderno.get", JsonUtils.toJsonString(params));
            if("0".equals(response.getResultCode())){
                order = JsonUtils.parseObject(response.getResult(), OrderExtVo.class);
                order.setTotalRealAmount(payAmount.intValue());
                order.setPayRealAmount(payAmount.intValue());
                order.setPayAppId(appId);
                order.setPayTime(format.format(new Date()));
                order.setUpdateTime(format.format(new Date()));
                order.setPaymentDealId(tradeNo);
                order.setPayStatus((short) 3);
                order.setOrderStatus((short) 3);
                order.setIsPayHandled(1);//支付是否通知并处理0：否，1：是

                //调用支付结果通知
                Map<String, String> datas = new HashMap<>();
                datas.put("hospital_code" , order.getOrgCode());
                datas.put("branch_code" , order.getBarcode());
                datas.put("order_no" , order.getOrderNo());
                datas.put("payment_deal_id" , order.getPaymentDealId());
                datas.put("out_order_no" , order.getOutOrderNo());
                datas.put("pay_status" , String.valueOf(order.getPayStatus()));
                datas.put("pay_time" , order.getPayTime());//???
                datas.put("order_type" , String.valueOf(order.getOrderType()));
                datas.put("pay_mode" , String.valueOf(order.getPayMode()));
                datas.put("pay_amount" , String.valueOf(order.getPayAmount()));

                Response resultNotice = null;
                try {
                    resultNotice = asmService.paymentAsmResultNotice(JsonUtils.toJsonString(datas));
                    logger.info(">> Get PaymentResultNotice reslut_code:" + resultNotice.getResultCode() + " --- relsut_Message:" + resultNotice.getResultMessage());
                } catch (Exception e) {
                    logger.error("[AsmAlipayMessageListener.GetPaymentAsmResultNotice === ]" , e);
                }

                //更改订单状态
                response = BaseService.callHumpFromInternal("yyt.base.order.update", JsonUtils.toJsonString(order));
                if("0".equals(response.getResultCode())){
                    logger.info(orderNo + "订单更新成功！");
                }
            }else{
                logger.info("自助机阿里支付回调,未查询到交易订单->"+orderNo);
            }
        } catch (Exception e) {
            logger.error("自助机阿里支付回调, 报错", e);
        }

        logger.info("自助机阿里支付回调结束");
    }
}
